﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：手机
/// </summary>
public sealed class IsPhoneAttribute : ValidationAttribute
{
    /// <summary>
    /// 手机验证规则
    /// </summary>
    public IsPhoneAttribute()
    {
        this.ErrorMessage = "{0}:请输入正确的手机号!";
    }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="msg">异常消息</param>
    public IsPhoneAttribute(string msg)
    {
        this.ErrorMessage = msg;
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            Regex r = new Regex(@"^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$");
            if (!r.IsMatch(value + ""))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
